<template>
    <div id="source">
        <el-row class="title" v-if="showBasicMsg">
            <span style="padding-left: 20px">{{ treeCurrentData.indexType == '2' ? '产品类型：' : '来源类型：' }}</span>
            <span style="padding-right: 20px">{{ searchParams.typeName }}</span>
            <span>{{ treeCurrentData.indexType == '2' ? '来源产品：' : '来源名称：' }}</span>
            <span>{{ searchParams.label || '--' }}</span>
            <span v-if="treeCurrentData.indexType == '2'" style="padding-left: 20px">成立日期：</span>
            <span v-if="treeCurrentData.indexType == '2'">{{ searchParams.setupDate || '--' }}</span>
        </el-row>

        <div style="height: calc(100% - 40px)" :style="{ height: ['3', '4'].includes(treeCurrentData.level) ? 'calc(100% - 80px)' : '100%' }">
            <!-- 表格工具栏 -->
            <div class="table-toolbar">
                <el-button
                    v-if="['3', '4'].includes(treeCurrentData.level) && treeCurrentData.indexType !== '2'"
                    type="primary"
                    @click="handleAddFileBtn('新增')"
                >
                    新增文件
                </el-button>
                <el-button type="primary" size="mini" @click="handleBtn('import')">{{ importBtnName }}</el-button>
                <el-button v-if="treeCurrentData.indexType !== '2'" size="mini" @click="handleBtn('deletes')">批量删除</el-button>
                <el-button
                    v-if="(treeCurrentData.level === '3' && treeCurrentData.indexType !== '2') || treeCurrentData.level === '4'"
                    size="mini"
                    @click="handleBtn('operatingRecord')"
                >
                    操作记录
                </el-button>
                <el-button
                    v-if="treeCurrentData.level === '4' && treeCurrentData.indexType == '2'"
                    size="mini"
                    @click="handleBtn('todo')"
                >
                    待办处理
                </el-button>
            </div>

            <RiskTable
                ref="risk-table"
                :tableData="tableData"
                :tableConfig="tableConfig"
                :column="showColumns"
                :paging="paging"
                :tableKey="tableKey"
                v-loading="tableLoading"
                style="height: calc(100% - 60px)"
                @page-change="getTableData"
            >
                <template #articleName="{ row }">
                    <span>
                        <div v-show="row.finish === '0' && treeCurrentData.indexType === '2'" class="new-style"></div>
                        <!-- <span class="new" v-show="row.finish === '0' && treeCurrentData.indexType === '2'">NEW</span> -->
                        {{ row.articleName }}
                    </span>
                </template>
                <template #fileName="{ row }">
                    <span>{{ row.fileName.length == 0 ? '--' : row.fileName.join(',') }}</span>
                </template>
                <template #valid="{ row }">
                    <el-switch v-model="row.valid" active-value="1" inactive-value="0" @change="handleValid($event, row)"> </el-switch>
                </template>
                <template #operation="{ row }">
                    <a v-if="treeCurrentData.indexType !== '2'" href="javascript:;" @click="handleBtn('edit', row)">修改</a>
                    <a href="javascript:;" @click="handleBtn('downLoad', row)">下载</a>
                    <a v-if="treeCurrentData.indexType !== '2'" href="javascript:;" @click="handleBtn('delete', row)">删除</a>
                    <!-- <a v-if="treeCurrentData.indexType === '2'" href="javascript:;">
                        {{ row.finish === '0' ? '未完成' : (row.finish === '1' ? '已完成' : (row.finish === '3' ? '已关闭' : '--')) }}
                    </a> -->
                </template>
            </RiskTable>
        </div>

        <!-- 操作记录弹窗 -->
        <EntryRecordDialog
            :entryRecordDialog="operatingRecordVisible"
            :entryRecordItem="treeCurrentData"
            @emitEntryRecordDialog="emitEntryRecordDialog"
        ></EntryRecordDialog>

        <!-- 附件上传弹窗 -->
        <el-dialog title="附件上传内容填写" :visible.sync="attachementDialog" width="55%" :close-on-click-modal="false">
            <div>
                <el-form :inline="true" :model="indexDetails" :label-position="right" label-width="100px">
                    <el-row class="form-row" v-if="['监管类', '制度解读类'].includes(MenuName)">
                        <el-col :span="12">
                            <el-form-item label="版本号">
                                <span style="position: absolute; left: -10px; color: red">*</span>
                                <el-input v-model="indexDetails.versionNumber" size="mini" style="width: 220px" maxlength="20"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="是否有效">
                                <el-select v-model="indexDetails.valid" placeholder="请选择" style="width: 220px" size="mini">
                                    <el-option label="有效" value="1"></el-option>
                                    <el-option label="无效" value="0"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="form-row" v-else-if="MenuName == '合同类'">
                        <el-col :span="12">
                            <el-form-item label="合同名称">
                                <span style="position: absolute; left: -10px; color: red">*</span>
                                <el-input v-model="indexDetails.versionNumber" size="mini" style="width: 220px" maxlength="20"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="合同类型">
                                <span style="position: absolute; left: -10px; color: red">*</span>
                                <el-select v-model="indexDetails.productType" placeholder="请选择" style="width: 220px" size="mini" clearable>
                                    <el-option label="资产管理合同" value="1" key="1"></el-option>
                                    <el-option label="补充协议" value="2" key="2"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="form-row">
                        <el-col :span="12">
                            <el-form-item label="发布日期" v-if="['监管类', '制度解读类'].includes(MenuName)">
                                <el-date-picker
                                    v-model="indexDetails.issueDate"
                                    placeholder="选择日期"
                                    size="mini"
                                    style="width: 220px"
                                    format="yyyy-MM-dd"
                                    value-format="yyyyMMdd"
                                >
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="签署日期" v-else-if="MenuName == '合同类'">
                                <el-date-picker
                                    v-model="indexDetails.issueDate"
                                    placeholder="选择日期"
                                    size="mini"
                                    style="width: 220px"
                                    format="yyyy-MM-dd"
                                    value-format="yyyyMMdd"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="生效日期">
                                <el-date-picker
                                    v-model="indexDetails.effectiveDate"
                                    placeholder="选择日期"
                                    size="mini"
                                    style="width: 220px"
                                    format="yyyy-MM-dd"
                                    value-format="yyyyMMdd"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="form-row">
                        <el-col :span="12">
                            <el-form-item label="迁移条文">
                                <el-select
                                    v-model="indexDetails.moveIndexArticleCode"
                                    filterable
                                    clearable
                                    placeholder="请选择"
                                    size="mini"
                                    style="width: 220px"
                                    @change="changeMovedIndexSource"
                                >
                                    <el-option
                                        :label="item.articleName"
                                        :value="item.articleCode"
                                        v-for="item in indexSourceCodeSelect1"
                                        :key="item.articleCode"
                                        >{{ item.articleName }}</el-option
                                    >
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="迁移版本" v-if="['监管类', '制度解读类'].includes(MenuName)">
                                <el-select
                                    v-model="indexDetails.moveIndexArticleDetailsCode"
                                    filterable
                                    clearable
                                    placeholder="请选择"
                                    size="mini"
                                    style="width: 220px"
                                    @change="$forceUpdate()"
                                >
                                    <el-option
                                        :label="item.versionNumber"
                                        :value="item.articleDeatilsCode"
                                        v-for="item in moveIndexArticleCodeList"
                                        :key="item.articleDeatilsCode"
                                        >{{ item.versionNumber }}</el-option
                                    >
                                </el-select>
                            </el-form-item>
                            <el-form-item label="是否有效" v-else-if="MenuName == '合同类'">
                                <el-select v-model="indexDetails.valid" placeholder="请选择" style="width: 220px" size="mini">
                                    <el-option label="有效" value="1"></el-option>
                                    <el-option label="无效" value="0"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="form-row">
                        <el-col :span="12">
                            <el-form-item label="附件">
                                <el-upload
                                    :multiple="true"
                                    :action="actionUrl"
                                    :headers="headerObj"
                                    :with-credentials="true"
                                    list-type="text"
                                    :show-file-list="false"
                                    :on-success="
                                        (res, file, fileList) => {
                                            return uploadFileSuccess(res, file, fileList, '执行标准');
                                        }
                                    "
                                    :on-error="
                                        (res, file, fileList) => {
                                            return uploadFileError(res, file, fileList, '执行标准');
                                        }
                                    "
                                >
                                    <el-button size="small" icon="el-icon-plus" style="border: none">添加文件</el-button>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <UploadFileShow
                        style="margin-left: 60px"
                        :fileList="fileList1"
                        @emitDownLoadFile="downLoadFileBtn2"
                        @emitConfirmDelFile="confirmDelFile1"
                    ></UploadFileShow>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="insertSourceDetails">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 删除弹窗 -->
        <yh-dialog title="警告" :visible.sync="deleteVisible" width="600px" drag>
            <div>
                <!-- {{ checkedRows.map(item => item.id + '(' + item.dataSourceName + ')').join(',') }} -->
                是否删除所选来源文件？
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="deleteVisible = false" size="mini">取 消</el-button>
                <el-button @click="handleDelete" :loading="delLoading" size="mini" type="primary">确 定 </el-button>
            </div>
        </yh-dialog>
        <!-- 待办处理弹窗 -->
        <yh-dialog title="待办处理" :visible.sync="todoVisible" width="650px">
            <div v-if="todoVisible">
                <div><i style="color: #f4ea2a; font-size: 22px" class="el-icon-info"></i> 请注意：当合同有效无需处理待办时，通过关闭选项，可实现合规条款库、交易系统、事后系统待办关闭功能</div>
                <div style="margin: 15px 0;">待办任务：<el-radio v-model="modifyType" label="5">关闭</el-radio><el-radio v-model="modifyType" label="6">开启</el-radio></div>
                <div style="display: flex">
                    <div style="width: 80px">{{modifyType=='5'?'关闭原因：':'开启原因'}}</div>
                    <span style="position: absolute; left: 83px; color: red">*</span>
                    <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="请输入内容" v-model="reason"></el-input>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleTodo('cancel')" size="mini">取 消</el-button>
                <el-button @click="handleTodo('confirm')" size="mini" type="primary">确 定 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import UploadFileShow from '../commom/upload-file-show.vue';
import DeletionConfirmationDialog from '../commom/deletion-confirmation-dialog.vue';
import { dateFormat, timeFormat, getConfigItem } from '@/utils/tools';
import { getUser } from '@/utils/user-util';
import { downLoadFile } from '@/utils/request';
import XEUtils from 'xe-utils';
import moment from 'moment';
import JSEncrypt from 'jsencrypt';
import EntryRecordDialog from './entry-record-dialog.vue';
import RiskTable from '@/common/components/risk-table-plus.vue';
import { ColumnVO, PageVO, TableConfigVO } from '@/common/vo';

@Component({
    name: 'SourceDocumentDialog',
    components: {
        RiskIconButton,
        UploadFileShow,
        DeletionConfirmationDialog,
        EntryRecordDialog,
        RiskTable,
    },
})
export default class SourceDocumentDialog extends Vue {
    BASE_URL_API = getConfigItem('BASE_URL_API');
    dateFormat = dateFormat;
    // @Prop() treeCurrentData;
    @Prop() indexClauseList;
    @Prop() MenuName;
    @Prop() treeCurrentData: any; // 选中树节点

    actionUrl: string = ''; // 资管附件云url
    rsaPassWord: any = null; // 资管附件云密钥

    productTypes: any = {
        '1': '资产管理合同',
        '2': '补充协议',
    };

    searchParams: any = {
        parentId: '', // 指标类型：1:外规类指标、2:产品类指标
        label: '', // 指标来源名称
        lableChild: '',
        typeName: '',
        setupDate: '',
    };

    tableData: any[] = [];
    paging: PageVO = { currentPage: 1, pageSize: 50, total: 0 };
    tableLoading: boolean = false;
    tableConfig: TableConfigVO = {
        rowKey: 'articleDeatilsCode', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableKey: number = 0;
    columns1: ColumnVO[] = [
        {
            type: 'checkbox',
            selectedAll: false,
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        {
            title: '序号',
            field: 'articleDeatilsCode',
            width: 85,
        },
        {
            title: '来源名称',
            field: 'articleName',
            minWidth: 120,
        },
        {
            title: '版本号',
            field: 'versionNumber',
            minWidth: 120,
        },
        {
            title: '文件名称',
            field: 'fileName',
            minWidth: 170,
        },
        {
            title: '发布日期',
            field: 'issueDate',
            align: 'center',
            minWidth: 120,
            render: (value, record) => dateFormat(value),
        },
        {
            title: '生效日期',
            field: 'effectiveDate',
            align: 'center',
            minWidth: 120,
            render: (value, record) => dateFormat(value),
        },
        {
            title: '是否有效',
            field: 'valid',
            align: 'center',
            minWidth: 100,
        },
        {
            title: '维护人',
            field: 'upload',
            minWidth: 120,
        },
        {
            title: '维护日期',
            field: 'modifyDate',
            align: 'center',
            minWidth: 120,
            render: (value, record) => dateFormat(value),
        },
        { title: '操作', field: 'operation', minWidth: 150, width: 150, align: 'center', fixed: 'right' },
    ];
    columns2: ColumnVO[] = [
        {
            type: 'checkbox',
            selectedAll: false,
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        {
            title: '来源名称',
            field: 'articleName',
            minWidth: 120,
        },
        {
            title: '序号',
            field: 'articleDeatilsCode',
            width: 85,
        },
        {
            title: '合同类型',
            field: 'productType',
            align: 'center',
            minWidth: 120,
            render: (value, record) => this.productTypes[value],
        },
        {
            title: '合同名称',
            field: 'versionNumber',
            minWidth: 170,
        },
        {
            title: '签署日期',
            field: 'issueDate',
            align: 'center',
            minWidth: 120,
            render: (value, record) => dateFormat(value),
        },
        {
            title: '生效日期',
            field: 'effectiveDate',
            align: 'center',
            minWidth: 120,
            render: (value, record) => dateFormat(value),
        },
        {
            title: '是否有效',
            field: 'valid',
            align: 'center',
            minWidth: 100,
        },
        {
            title: '维护人',
            field: 'upload',
            minWidth: 120,
        },
        {
            title: '维护日期',
            field: 'modifyDate',
            align: 'center',
            minWidth: 120,
            render: (value, record) => dateFormat(value),
        },
        {
            title: '任务状态',
            field: 'finish',
            align: 'center',
            minWidth: 120,
            render: (value, record) => value === '0' ? '未完成' : (value === '1' ? '已完成' : (value === '3' ? '已关闭' : '--')),
        },
        { title: '操作', field: 'operation', minWidth: 100, width: 120, align: 'center', fixed: 'right' },
    ];
    showColumns: ColumnVO[] = [];

    checkRowKeys: string[] = [];

    indexSourceStorage: any[] = []; // 来源类型仓库

    operatingRecordVisible: boolean = false; // 操作记录弹窗
    deleteVisible: boolean = false;
    attachementVisible: boolean = false;

    delLoading: boolean = false;

    private dialogVisible: boolean = false;
    private attachementDialog: boolean = false;
    addFileBtn: boolean = false; // 新增文件btn
    indexSourceCategoryDetail = []; // 来源详情信息
    private indexSourceCodeSelect1 = []; // 来源名称select
    private moveIndexArticleCodeList = []; // 迁移版本号select
    typeItem: string = ''; // 新增、编辑
    fileList1 = []; // 附件
    multipleitem = []; // table多选
    delBtnDisabled: boolean = false;
    delConfirmationDialog: boolean = false;
    headerObj = {
        Authentication: getUser().sessionId,
    };
    indexSourceCategoryDetailPo = {
        indexType: '1', // 指标类型：1:外规类指标、2:产品类指标
        parentId: '', // 来源类型
        label: '', // 指标来源名称
        lableChild: '',
    };
    validTable: string = '是';
    indexDetails = {
        // 来源详情信息
        articleCode: '',
        articleDeatilsCode: '',
        indexDirectoryCode: '',
        effectiveDate: '',
        fileCode: [],
        fileName: [],
        issueDate: '',
        moveIndexArticleCode: '',
        moveIndexArticleDetailsCode: '',
        valid: '1',
        versionNumber: '',
        // signDate: '',
        files: [],
        indexType: '',
        productType: '',
    };
    addDisabled: boolean = false;
    moveIndexSourceIs: boolean = false;
    delContent: string = '是否删除所选来源文件？';
    title = '';
    delData = {
        singData: '',
        moreData: [],
        type: '',
    };
    flag = false; // 判断是否已使用迁移条文
    reason = '';
    modifyType = '5';
    todoVisible: boolean = false;

    created() {
        this.actionUrl = this.BASE_URL_API + '/apiAssetFile/upload';
        var encryptor = new JSEncrypt(); // 创建加密对象实例
        // 之前ssl生成的公钥，复制的时候要小心不要有空格
        var pubKey =
            'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI1/pR72vGeQoQ8YxKVrDzV6RriOkNkW0UWw4JgXhH417lULhKMQWK3GeJW+Tg0kHlhpx4iQNxrEPlroCqZfylgPI+x0AohcnvkY52VGQGLnms2tMefBKdz2BHUAp7MdF7GsGtpiHWSZbEWk5onkB7pH8Q0KlNAB+7BoNTj9MOywIDAQAB';
        encryptor.setPublicKey(pubKey); // 设置公钥
        this.rsaPassWord = encryptor.encrypt('zszg@zgssfkxt'); // 对内容进行加密]
    }

    mounted() {
        this.getTableData();
    }

    /**
     * 监听树节点切换
     */
    @Watch('treeCurrentData', { immediate: true, deep: true })
    watchTreeCurrentData(newData, oldData) {
        this.$nextTick(() => {
            (this.$refs['risk-table'] as any).resetCheckRowKeys();
        });
        if (newData.indexType === '2') {
            this.showColumns = this.columns2;
            this.searchParams.label = newData.label + '(' + newData.productCode + ')';
        } else {
            this.showColumns = this.columns1;
            this.searchParams.label = newData.label;
        }
        // 获取基础信息
        this.searchParams.parentId = newData.indexType === '2' ? newData.productTypes : newData.parentCode;
        this.searchParams.setupDate = dateFormat(newData.setupDate);
        // 重置页码
        this.paging = { currentPage: 1, pageSize: 50, total: 0 };

        this.tableKey++;
        this.getTableData();
        this.getIndexSourceList();
    }

    get importBtnName() {
        const enums = { '1': '监管条款导入', '2': '合同条款导入', '3': '合规条款导入' };
        return enums[this.treeCurrentData.indexType];
    }

    get showBasicMsg() {
        // 资管类解毒类 展示 level = 3
        if (['1', '3'].includes(this.treeCurrentData.indexType) && this.treeCurrentData.level === '3') {
            return true;
        } else if (['2'].includes(this.treeCurrentData.indexType) && this.treeCurrentData.level === '4') {
            // 合同类 展示 level = 4
            return true;
        } else {
            return false;
        }
    }

    getTableData(): void {
        this.tableLoading = true;

        if (sessionStorage.getItem('jumpParam-clauseCode') || sessionStorage.getItem('jumpParam-defaultFundCode')) {
            // 说明是第一次进来 由于缺失树节点的其他字段(indexType) 这次请求忽略
            return;
        }

        let data: any = { paging: this.paging };
        // 第一层传 indexType
        // 第二层传 indexDirectoryCode (实际tree id)
        // 第三层传 articleCode (实际tree id)
        if (this.treeCurrentData.level === '1') {
            data.indexType = this.treeCurrentData.indexType;
        }
        if (this.treeCurrentData.level === '2' || (this.treeCurrentData.level === '3' && this.treeCurrentData.indexType === '2')) {
            data.indexDirectoryCode = this.treeCurrentData.id;
            data.indexType = this.treeCurrentData.indexType;
        }
        if ((this.treeCurrentData.level === '3' && this.treeCurrentData.indexType !== '2') || this.treeCurrentData.level === '4') {
            data.articleCode = this.treeCurrentData.id;
        }
        this.$axios({ url: '/zhiguan/indexArticle/articleDetails/query', method: 'post', data })
            .then((res: any) => {
                this.tableData = res.list || [];
                this.paging.total = res.total;
            })
            .finally(() => {
                this.tableLoading = false;
                // this.tableData = [
                //     {
                //         articleCode: '40413',
                //         articleDeatilsCode: '3608',
                //         fileCode: ['11324', '11325'],
                //         fileName: ['同步SQL.txt', 'jmap.txt'],
                //         flag: false,
                //         indexDirectoryCode: '193',
                //         indexType: '1',
                //         modifyDate: 20230815,
                //         modifyTime: 220027,
                //         modifyUser: '管六元',
                //         moveIndexArticleCode: '28047',
                //         moveIndexArticleDetailsCode: '4271',
                //         valid: '1',
                //         versionNumber: '242342',
                //         i: '1',
                //         finish: '0',
                //         articleName: '!@?!?@!?',
                //     },
                // ];
            });
    }
    getTableData2(): void {
        this.tableLoading = true;

        let data: any = { paging: this.paging };
        // 第一层传 indexType
        // 第二层传 indexDirectoryCode (实际tree id)
        // 第三层传 articleCode (实际tree id)
        if (this.treeCurrentData.level === '1') {
            data.indexType = this.treeCurrentData.indexType;
        }
        if (this.treeCurrentData.level === '2' || (this.treeCurrentData.level === '3' && this.treeCurrentData.indexType === '2')) {
            data.indexDirectoryCode = this.treeCurrentData.id;
            data.indexType = this.treeCurrentData.indexType;
        }
        if ((this.treeCurrentData.level === '3' && this.treeCurrentData.indexType !== '2') || this.treeCurrentData.level === '4') {
            data.articleCode = this.treeCurrentData.id;
        }
        this.$axios({ url: '/zhiguan/indexArticle/articleDetails/query', method: 'post', data })
            .then((res: any) => {
                this.tableData = res.list || [];
                this.paging.total = res.total;
                if (res.list.length == 0) {
                    this.$emit('deleteAllList', this.treeCurrentData);
                }
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }

    /**
     * 获取来源类型
     */
    getIndexSourceList(): void {
        if (['1', '2'].includes(this.treeCurrentData.level)) {
            return;
        }

        // 监管类 解读类
        if (this.treeCurrentData.indexType != '2') {
            this.$axios({
                url: '/zhiguan/indexArticle/directory/queryName',
                method: 'post',
                data: { indexDirectory: this.treeCurrentData.parentCode },
            }).then((res: any) => {
                this.indexSourceStorage = [res];
                this.searchParams.typeName = res.indexName;
            });
        }
        // 合同类
        if (this.treeCurrentData.indexType == '2') {
            this.indexSourceStorage = [
                { indexDirectoryCode: '5', indexName: '公募', level: '3', indexType: '2' },
                { indexDirectoryCode: '6', indexName: '私募单一', level: '3', indexType: '2' },
                { indexDirectoryCode: '7', indexName: '私募集合', level: '3', indexType: '2' },
                { indexDirectoryCode: '8', indexName: '公募', level: '3', indexType: '2' },
                { indexDirectoryCode: '9', indexName: '私募单一', level: '3', indexType: '2' },
                { indexDirectoryCode: '10', indexName: '私募集合', level: '3', indexType: '2' },
            ];
            this.searchParams.typeName = this.indexSourceStorage.find(i => i.indexDirectoryCode === this.searchParams.parentId).indexName || '--';
        }
    }

    /**
     * 按钮操作事件
     */
    handleBtn(type: string, row?: any): void {
        if (type === 'delete') {
            this.checkRowKeys = [row.articleDeatilsCode];
            this.deleteVisible = true;
        } else if (type === 'deletes') {
            this.checkRowKeys = (this.$refs['risk-table'] as any).checkRowKeys;
            if (this.checkRowKeys.length < 1) {
                this.yh_message_warn('请选择来源文件！');
                return;
            }

            this.deleteVisible = true;
        } else if (type === 'import') {
            this.$emit('enableClause');
        } else if (type === 'operatingRecord') {
            this.operatingRecordVisible = true;
        } else if (type === 'downLoad') {
            if (row.fileCode[0] == null) {
                this.$message.warning('来源附件为空！');
                return;
            }

            let url = '/apiAssetFile/downLoad';
            if (this.treeCurrentData.indexType === '2') {
                url = '/apiAssetFile/productDownLoad';

                this.$axios({ method: 'post', url: '/apiAssetFile/queryCount', data: { fileId: [row.fileCode[0]] } }).then((res: any) => {
                    if (res > 0) {
                        downLoadFile({
                            url: '/apiAssetFile/downLoad',
                            method: 'post',
                            data: { fileId: [row.fileCode[0]], fileName: row.fileName[0], passWord: this.rsaPassWord },
                        });
                    } else {
                        downLoadFile({
                            url,
                            method: 'post',
                            data: { fileId: [row.fileCode[0]], fileName: row.fileName[0], passWord: this.rsaPassWord },
                        });
                    }
                });
            } else {
                downLoadFile({
                    url,
                    method: 'post',
                    data: { fileId: [row.fileCode[0]], fileName: row.fileName[0], passWord: this.rsaPassWord },
                });
            }
        } else if (type === 'edit') {
            this.openAttachementDialog(row, '修改');
        } else if (type === 'todo') {
            let checkRowKeys = (this.$refs['risk-table'] as any).checkedRows;
            if (checkRowKeys.length < 1) {
                this.yh_message_warn('请选择来源文件！');
                return;
            }
            // let arr = []
            // for (let i = 0; i < checkRowKeys.length; i++) {
            //     if (checkRowKeys[i].finish == '3') {
            //         arr.push(checkRowKeys[i].articleDeatilsCode)
            //     }
            // }
            // if (arr.length > 0) {
            //     this.yh_message_warn('已选数据中包含已关闭条款：' + arr.join(','));
            //     return
            // }
            this.todoVisible = true;
        }
    }

    handleTodo(type) {
        if (type == 'cancel') {
            this.todoVisible = false;
        } else if (type == 'confirm') {
            this.checkRowKeys = (this.$refs['risk-table'] as any).checkRowKeys;
            if (this.reason == '') {
                this.yh_message_warn(this.modifyType == '6' ? '开启原因不可为空！' : '关闭原因不可为空！');
                return;
            }
            let checkRowRows = (this.$refs['risk-table'] as any).checkedRows;
            // 选择关闭：不可有已关闭的条款
            if (this.modifyType == '5') {
                let arr = []
                for (let i = 0; i < checkRowRows.length; i++) {
                    if (checkRowRows[i].finish == '3') {
                        arr.push(checkRowRows[i].articleDeatilsCode)
                    }
                }
                if (arr.length > 0) {
                    this.yh_message_warn('已选数据中包含已关闭条款：' + arr.join(','));
                    return
                }    
            }
            // 选择开启： 只传已关闭的条款
            if (this.modifyType == '6') {
                let arr2 = []
                for (let i = 0; i < checkRowRows.length; i++) {
                    if (checkRowRows[i].finish != '3') {
                        arr2.push(checkRowRows[i].articleDeatilsCode)
                    }
                }
                if (arr2.length > 0) {
                    this.yh_message_warn('已选数据中包含未完成/已完成条款：' + arr2.join(','));
                    return
                }    
            }

            this.$axios({ 
                url: '/zhiguan/indexArticle/todoProcessing', 
                method: 'post', 
                data: {
                    articleDeatilsCodeList: this.checkRowKeys,
                    reason: this.reason,
                    modifyType: this.modifyType
                }
            }).then((res: any) => {
                if (this.modifyType == '6' && res.length > 0) {
                    this.yh_message_warn('当前' + res + '合同/协议下已完成待办，无法开启待办内容!');
                } else {
                    this.yh_message_success('修改成功!');
                }
                this.reason = '';
                this.modifyType = '5';
                this.todoVisible = false;
                this.getTableData();
                this.$emit('emitHandleVaild');
                this.$nextTick(() => {
                    (this.$refs['risk-table'] as any).resetCheckRowKeys();
                });
            });
        }
    }

    /**
     * 是否有效 开关变动事件
     */
    handleValid(val, row) {
        let data = row;
        if (val === '0') {
            this.$confirm('请注意: 当合同无效无需处理待办时，通过无效选项, 可实现条款为停用状态，存量待办任务将关闭处理', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    data.valid = val;
                    this.$axios({ url: '/zhiguan/indexArticle/articleDetails/update', method: 'post', data }).then((res: any) => {
                        this.yh_message_success('修改成功!');
                        this.getTableData();
                        this.$emit('emitHandleVaild');
                    });
                })
                .catch(() => {
                    data.valid = '1';
                    this.$message({
                        type: 'info',
                        message: '已取消修改!',
                    });
                });
        } else {
            data.valid = val;
            this.$axios({ url: '/zhiguan/indexArticle/articleDetails/update', method: 'post', data }).then((res: any) => {
                this.yh_message_success('修改成功!');
                this.getTableData();
                this.$emit('emitHandleVaild');
            });
        }
    }

    /**
     * 操作记录回调事件
     */
    emitEntryRecordDialog(param): void {
        this.operatingRecordVisible = param;
    }

    /**
     * 删除事件
     */
    handleDelete(): void {
        this.delLoading = true;
        this.$axios({
            url: '/zhiguan/indexArticle/articleDetails/delete',
            method: 'post',
            data: { articleDeatilsCodeList: this.checkRowKeys },
        })
            .then((res: any) => {
                this.yh_message_success('删除成功!');
            })
            .finally(() => {
                this.delLoading = false;
                this.deleteVisible = false;
                this.getTableData2();

                this.checkRowKeys = [];
                this.$nextTick(() => {
                    (this.$refs['risk-table'] as any).resetCheckRowKeys();
                });

                this.$emit('emitHandleVaild');
            });
    }

    handleSource(parameter) {
        if (parameter == 'cancel') {
            this.$emit('emitSource', false, false);
            return;
        }
        if (this.treeCurrentData.level == 2) {
            if (this.indexSourceCategoryDetailPo.label == '') {
                this.yh_message_warn(this.treeCurrentData.indexType == '2' ? '来源产品不可为空' : '来源名称不可为空');
                return;
            }
            this.insertSourceDetails();
        } else {
            this.$emit('emitSource', false, false);
        }
    }

    @Watch('attachementDialog')
    watchAttachementDialog(val) {
        if (val == true) {
            this.moveIndexArticleCodeList = [];
            this.indexDetails.articleCode = this.treeCurrentData.id;
            this.getIndexSourceSelect1(this.treeCurrentData.indexType);
        } else if (val == false) {
            this.moveIndexArticleCodeList = [];
            this.fileList1 = [];
            this.indexDetails = {
                // 来源详情信息
                articleCode: this.treeCurrentData.id,
                indexDirectoryCode: '',
                articleDeatilsCode: '',
                versionNumber: '',
                valid: '1',
                issueDate: '',
                // signDate: '',
                effectiveDate: '',
                moveIndexArticleCode: '',
                moveIndexArticleDetailsCode: '',
                fileCode: [],
                files: [],
                fileName: [],
                indexType: '',
                productType: '',
            };
            this.moveIndexSourceIs = false;
        }
    }
    @Watch('indexClauseList', { immediate: true, deep: true })
    watchIndexClauseList(val) {
        if (this.indexClauseList.length > 0) {
            this.delBtnDisabled = true;
        } else {
            this.delBtnDisabled = false;
        }
    }

    // 查询条文详情信息/articleDetails/query
    getSourceDetails() {
        this.$axios
            .post('/zhiguan/indexArticle/articleDetails/query', {
                articleCode: this.indexDetails.articleCode,
            })
            .then((res: any) => {
                this.indexSourceCategoryDetail = [];
                res.forEach(item => this.indexSourceCategoryDetail.push(item));
            });
    }
    // 新增来源详情信息
    insertSourceDetails() {
        if (this.indexDetails.versionNumber == '' && ['监管类', '制度解读类'].includes(this.MenuName)) {
            this.yh_message_warn('版本号不可为空');
            return;
        }
        if (this.indexDetails.versionNumber == '' && ['合同类'].includes(this.MenuName)) {
            this.yh_message_warn('合同名称不可为空');
            return;
        }
        if (this.indexDetails.productType == '' && ['合同类'].includes(this.MenuName)) {
            this.yh_message_warn('合同类型不可为空');
            return;
        }
        if (this.indexDetails.moveIndexArticleCode != '' && this.indexDetails.moveIndexArticleDetailsCode == '') {
            this.yh_message_warn('迁移版本号不可为空');
            return;
        }
        this.indexDetails.fileCode = [];
        this.indexDetails.fileName = [];
        this.indexDetails.files = [];
        if (this.fileList1) {
            this.fileList1.forEach(item => {
                this.indexDetails.fileCode.push(item.fileNo);
                this.indexDetails.fileName.push(item.name);
                this.indexDetails.files.push({
                    fileNo: item.fileNo,
                    fileName: item.name,
                });
            });
        }
        let dataList = {};
        dataList = {
            // 来源详情信息
            articleCode: this.indexDetails.articleCode,
            articleDeatilsCode: this.indexDetails.articleDeatilsCode,
            effectiveDate: this.indexDetails.effectiveDate,
            fileCode: this.indexDetails.fileCode,
            fileName: this.indexDetails.fileName,
            issueDate: this.indexDetails.issueDate,
            versionNumber: this.indexDetails.versionNumber,
            valid: this.indexDetails.valid,
            indexType: this.treeCurrentData.indexType,
            moveIndexArticleCode: this.indexDetails.moveIndexArticleCode,
            moveIndexArticleDetailsCode: this.indexDetails.moveIndexArticleDetailsCode,
            indexDirectoryCode: this.treeCurrentData.indexType == '2' ? this.treeCurrentData.productTypes : this.treeCurrentData.parentCode,
            productType: this.indexDetails.productType,
        };
        let flag;

        if (this.typeItem == '新增') {
            if (this.treeCurrentData.indexType != '2') {
                if (this.indexDetails.moveIndexArticleCode != '' && this.indexDetails.moveIndexArticleDetailsCode != '') {
                    flag = true;
                } else {
                    flag = false;
                }
            } else {
                if (this.indexDetails.moveIndexArticleCode != '') {
                    flag = true;
                } else {
                    flag = false;
                }
            }

            this.$axios.post('/zhiguan/indexArticle/articleDetails/insert', { ...dataList, flag: flag }).then((res: any) => {
                this.yh_message_success('新增成功!');
                this.attachementDialog = false;
                this.fileList1 = [];
                this.getTableData();
                this.getSourceDetails();
                this.$emit('emitSource', true, true);
            });
        } else if (this.typeItem == '修改') {
            let flag;
            if (['1', '3'].includes(this.treeCurrentData.indexType)) {
                if (this.moveIndexSourceIs == false && this.indexDetails.moveIndexArticleCode && this.indexDetails.moveIndexArticleDetailsCode) {
                    flag = true;
                } else {
                    flag = false;
                }
            } else {
                if (this.moveIndexSourceIs == false && this.indexDetails.moveIndexArticleCode) {
                    flag = true;
                } else {
                    flag = false;
                }
            }
            this.$axios
                .post('/zhiguan/indexArticle/articleDetails/update', { ...dataList, flag: flag })
                .then((res: any) => {
                    this.yh_message_success('修改成功!');
                    this.attachementDialog = false;
                    this.fileList1 = [];
                    this.getTableData();
                    this.getSourceDetails();
                    this.moveIndexSourceIs = false;
                    this.$emit('emitSource', true, true);
                })
                .catch(() => {
                    this.moveIndexSourceIs = false;
                    this.attachementDialog = false;
                });
        }
    }

    // 迁移版本号
    getMoveVersionNums(indexCode) {
        this.$axios.post('/zhiguan/indexArticle/articleDetails/query', { articleCode: indexCode }).then((res: any) => {
            if (res) {
                this.moveIndexArticleCodeList = [];
                let articleDeatilsCodes = [];
                res.forEach(item => {
                    this.moveIndexArticleCodeList.push(item);
                    articleDeatilsCodes.push(item.articleDeatilsCode);
                });
                if (this.indexDetails.moveIndexArticleDetailsCode != '') {
                    if (!articleDeatilsCodes.includes(this.indexDetails.moveIndexArticleDetailsCode)) {
                        this.indexDetails.moveIndexArticleDetailsCode = '';
                    }
                }
            }
        });
    }
    // 迁移条文选择
    changeMovedIndexSource(param) {
        if (param) {
            this.getMoveVersionNums(param);
        } else {
            this.moveIndexArticleCodeList = [];
        }
        this.indexDetails.moveIndexArticleDetailsCode = '';
    }
    // 添加文件来源分类节点
    addFileSourceCategoryNode() {
        this.$axios.post('/indexSource/addFileSourceCategoryNode', { ...this.indexSourceCategoryDetailPo }).then((res: any) => {
            if (res) {
                this.indexDetails.articleCode = res;
                this.addFileBtn = true;
                this.yh_message_success('新增成功!');
                this.$emit('emitAddFileSourceCategoryNode');
                this.addDisabled = true;
            }
        });
    }
    // 新增文件Btn
    handleAddFileBtn(param) {
        this.attachementDialog = true;
        this.typeItem = param;
    }
    // 编辑来源文件
    openAttachementDialog(param1, param2) {
        this.indexDetails.articleCode = param1.articleCode;
        this.indexDetails.articleDeatilsCode = param1.articleDeatilsCode;
        this.$axios.post('/zhiguan/indexArticle/articleDetails/details', { articleDeatilsCode: param1.articleDeatilsCode }).then((res: any) => {
            this.indexDetails.files = [];
            if (this.treeCurrentData.indexType != '2') {
                if (res.moveIndexArticleCode && res.moveIndexArticleDetailsCode) {
                    this.moveIndexSourceIs = true;
                } else {
                    this.moveIndexSourceIs = false;
                }
            } else {
                if (res.moveIndexArticleCode) {
                    this.moveIndexSourceIs = true;
                } else {
                    this.moveIndexSourceIs = false;
                }
            }

            // if (res) {
            this.attachementDialog = true;
            this.typeItem = param2;
            let resList = res;
            if (resList.issueDate) {
                resList.issueDate = res.issueDate.toString();
            }
            if (resList.effectiveDate) {
                resList.effectiveDate = res.effectiveDate.toString();
            }
            this.indexDetails = resList;
            if (this.indexDetails.fileCode) {
                this.indexDetails.fileCode.forEach((element, index) => {
                    this.fileList1.push({
                        name: this.indexDetails.fileName[index],
                        fileNo: element,
                    });
                });
            }
            if (this.treeCurrentData.indexType != '2') {
                if (this.indexDetails.moveIndexArticleCode && this.indexDetails.moveIndexArticleDetailsCode) {
                    this.moveIndexSourceIs = true;
                } else {
                    this.moveIndexSourceIs = false;
                }
            } else {
                if (this.indexDetails.moveIndexArticleCode) {
                    this.moveIndexSourceIs = true;
                } else {
                    this.moveIndexSourceIs = false;
                }
            }

            if (this.indexDetails.moveIndexArticleCode) {
                this.getMoveVersionNums(this.indexDetails.moveIndexArticleCode);
            }
        });
    }
    // 下载
    downloadFileBtn(param1, param2) {
        let data = '';
        if (param2 == '单条下载') {
            if (param1.fileCode[0] == null) {
                this.$message.warning('来源附件为空！');
                return;
            }
            downLoadFile({
                url: '/apiAssetFile/downLoad',
                method: 'post',
                data: { fileId: [param1.fileCode[0]], fileName: param1.fileName[0], passWord: this.rsaPassWord },
            });
        } else {
            data = param1.fileNo;
            downLoadFile({
                url: '/system/download/file/' + data,
                method: 'get',
            });
        }
    }
    comfiredMove(param1, param2) {
        this.delData.moreData = [];
        this.delData.singData = '';
        if (param2 == '单个删除') {
            this.delData.singData = param1.articleDeatilsCode;
            this.delData.moreData = [];
            this.delData.type = param2;
        } else if (param2 == '批量删除') {
            if (param1.length == 0) {
                this.yh_message_warn('请选择来源文件！');
                return;
            }
            let data = [];
            param1.forEach(item => {
                this.delData.moreData.push(item.articleDeatilsCode);
            });
            this.delData.singData = '';
            this.delData.type = param2;
        }
        this.delConfirmationDialog = true;
    }
    handleRemove() {
        if (this.delData.type == '单个删除') {
            this.$axios
                .post('/zhiguan/indexArticle/articleDetails/delete', { articleDeatilsCodeList: [this.delData.singData] })
                .then((res: any) => {
                    this.yh_message_success('删除成功！');
                    this.delConfirmationDialog = false;
                    this.getTableData();
                    this.getSourceDetails();
                    this.$emit('emitHandleVaild');
                })
                .catch(() => {
                    this.delConfirmationDialog = false;
                });
        } else if (this.delData.type == '批量删除') {
            this.$axios
                .post('/zhiguan/indexArticle/articleDetails/delete', { articleDeatilsCodeList: this.delData.moreData })
                .then((res: any) => {
                    this.yh_message_success('删除成功！');
                    this.delConfirmationDialog = false;
                    this.getTableData();
                    this.getSourceDetails();
                    this.$emit('emitHandleVaild');
                })
                .catch(() => {
                    this.delConfirmationDialog = false;
                });
        }
    }
    // 删除确认窗口显示
    emitDialogVisible(param) {
        this.delConfirmationDialog = param;
    }
    // 多选
    clauseChangeEvent(checked, row, rowIndex) {
        this.multipleitem = [];
        checked.forEach(item => this.multipleitem.push(item));
    }
    // 迁移条文下拉
    getIndexSourceSelect1(data) {
        if (data != '2') {
            this.$axios.post('/zhiguan/indexArticle/article/query', { indexType: data }).then((res: any) => {
                this.indexSourceCodeSelect1 = [];
                res.forEach(item => this.indexSourceCodeSelect1.push(item));
            });
        } else {
            this.$axios.post('/zhiguan/indexArticle/directory/product/query', { indexType: data }).then((res: any) => {
                this.indexSourceCodeSelect1 = [];
                res.forEach(item =>
                    this.indexSourceCodeSelect1.push({
                        articleName: item.indexName,
                        articleCode: item.indexDirectoryCode,
                    })
                );
            });
        }
    }
    handleCommand(command) {
        let data = command.command;
        if (command.index == '0') {
            data.valid = 0;
        } else if (command.index == '1') {
            data.valid = 1;
        }
        this.$axios.post('/zhiguan/indexArticle/articleDetails/update', data).then((res: any) => {
            this.yh_message_success('修改成功!');
            this.getTableData();
            this.getSourceDetails();
            this.$emit('emitHandleVaild');
        });
    }
    beforeHandleCommand(index, command) {
        // index我这里是遍历的角标，即你需要传递的额外参数
        return {
            index: index,
            command: command,
        };
    }
    // 文件上传
    uploadFileSuccess(res, file, fileList, type) {
        if (res.returnMsg && res.returnMsg !== 'SUCCESS') {
            this.$message.warning(res.returnMsg);
            return;
        }
        this.fileList1.push({
            name: res.data.fileName,
            // url: res.data.relativePath,
            fileNo: res.data.fileId,
        });
    }
    uploadFileError(res, file, fileList, type) {
        this.$message.warning('文件格式不支持!');
    }
    // 下载文件
    downLoadFileBtn2(param) {
        // downLoadFile({
        //     url: '/apiAssetFile/downLoad/' + param.fileNo,
        //     method: 'get',
        // });
        if (param.fileNo == null) {
            this.$message.warning('来源附件为空！');
            return;
        }
        let url = '/apiAssetFile/downLoad';
        if (this.treeCurrentData.indexType === '2') {
            url = '/apiAssetFile/productDownLoad';

            this.$axios({ method: 'post', url: '/apiAssetFile/queryCount', data: { fileId: [param.fileNo] } }).then((res: any) => {
                if (res > 0) {
                    downLoadFile({
                        url: '/apiAssetFile/downLoad',
                        method: 'post',
                        data: { fileId: [param.fileNo], fileName: param.name, passWord: this.rsaPassWord },
                    });
                } else {
                    downLoadFile({
                        url,
                        method: 'post',
                        data: { fileId: [param.fileNo], fileName: param.name, passWord: this.rsaPassWord },
                    });
                }
            });
        } else {
            downLoadFile({
                url,
                method: 'post',
                data: { fileId: [param.fileNo], fileName: param.name, passWord: this.rsaPassWord },
            });
        }
    }
    // 删除已上传文件
    confirmDelFile1(param) {
        this.fileList1.forEach((item, index) => {
            if (item.fileNo == param.fileNo) {
                this.fileList1.splice(index, 1);
            }
        });
    }
}
</script>
<style lang="scss" scoped>
#source {
    width: 100%;
    height: 100%;
    padding: 0 10px;

    .title {
        height: 40px;
        line-height: 40px;
        background: #f7f8fc;
        margin: 20px 0 10px 0;
        color: #252a3a;

        span {
            font-size: 12px;
        }
    }

    .table-toolbar {
        padding: 10px 0;
    }

    a {
        color: #578bec;
        padding: 0 5px;
    }
}

/deep/ .el-form-item {
    margin: 0;

    .el-form-item__label {
        color: #575757;
        padding: 0;
    }

    .el-form-item__content {
        .el-input-group {
            vertical-align: inherit;
            display: inline-table;
        }
    }
}

/deep/ .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:after {
    display: none;
}

/deep/ .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
    content: '*' !important;
    color: red !important;
    margin-right: 4px !important;
}

.new {
    font-size: 10px;
    color: rgb(216, 30, 6);
    transform: scale(0.7);
    display: inline-block;
    font-weight: bold;
    margin-right: -5px;
}

.new-style {
    position: absolute;
    left: -5px;
    top: 10px;
    width: 12px;
    height: 12px;
    line-height: 12px;
    background: #ff7106;
    color: white;
    text-align: center;
    border-radius: 3px;
    font-weight: 700;
    font-size: 12px;
}

.new-style::after {
    content: 'N';
}
</style>
